﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Devtm.ServiceModel.Discovery;
using Devtm.ServiceModel.Proxy;


namespace Devtm.ServiceModel.UnitTest
{

    public class PoolService : IDisposable
    {


        // Init
        private Uri probeEndpointAddress;
        private Uri announcementEndpointAddress;
        private List<ServiceHost> _list = new List<ServiceHost>();
        private ServiceFactory factory;


        public ProxyConfiguration GetConfiguration<T>() { return factory.Configuration<T>(); }
        public T GetService<T>() { return factory.GetService<T>(); }


        public PoolService(Uri probeEndpointAddress, Uri announcementEndpointAddress)
        {

            this.probeEndpointAddress = probeEndpointAddress;
            this.announcementEndpointAddress = announcementEndpointAddress;

            // start DirectoryServer
            ServiceHost proxyServiceHost = DiscoveryProxyService.GetDiscoveryService(probeEndpointAddress, announcementEndpointAddress, new NetTcpBinding());
            proxyServiceHost.Open();

            // Start DirectoryClient
            Devtm.ServiceModel.Discovery.Discovery.ServiceDirectoriesClient probes = new Devtm.ServiceModel.Discovery.Discovery.ServiceDirectoriesClient(probeEndpointAddress);
            factory = new ServiceFactory(probes);

        }



        public PoolService AddService<T>()
        {
            ServiceHost r = new ServiceHost(typeof(T));
            r.AddAnnouncement(announcementEndpointAddress);
            r.Open();
            return this;
        }



        public PoolService AddService(Type service)
        {
            ServiceHost r = new ServiceHost(service);
            r.AddAnnouncement(announcementEndpointAddress);
            return this;
        }

        ~PoolService()
        {
            Dispose(false);
        }


        public void Dispose(bool disposing)
        {
            if (disposing)
            {

                foreach (ServiceHost item in _list)
                    (item as IDisposable).Dispose();

            }
        }

        public void Dispose()
        {
            Dispose(true);
        }

    }

}
